package com.tomato.study.rabbitmq.consumer.consumer;

import com.tomato.study.rabbitmq.core.constant.RabbitConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;

import java.io.IOException;


/**
 * 消费者监听队列，并消费消息
 * org.springframework.amqp.core.AcknowledgeMode
 * AcknowledgeMode.NONE：自动确认
 * AcknowledgeMode.AUTO：根据情况确认
 * AcknowledgeMode.MANUAL：手动确认
 * @author lizhifu
 * @date 2022/3/21
 */
@Component
@Slf4j
public class RabbitSimpleConsumer {
    @RabbitHandler
    @RabbitListener(queues = RabbitConstant.SIMPLE_QUEUE_NAME, ackMode = "MANUAL")
    public void simpleListener(String context, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
        log.info("RabbitSimpleConsumer simpleListener 接收消息：{},deliveryTag:{}",context,deliveryTag);
        // RabbitMQ的ack机制中，第二个参数返回true，表示需要将这条消息投递给其他的消费者重新消费
        channel.basicAck(deliveryTag, true);
        // 第三个参数true，表示这个消息会重新进入队列
//         channel.basicNack(deliveryTag, false, true);
    }
    @RabbitHandler
    @RabbitListener(queues = RabbitConstant.SIMPLE_QUEUE_TRANSACTION_NAME)
    public void simpleTransactionListener(String context) {
        log.info("RabbitSimpleConsumer simpleTransactionListener 接收消息：{}",context);
    }
}
